package br.unifor.cct.mia.coevolution.memory;

import java.util.ArrayList;
import java.util.Iterator;

import br.unifor.cct.mia.evolutionary.Individual;

public class RepeatableSharedMemory extends SharedMemory{

	private static final String SEMAPHORE = "S";
	private ArrayList memory;
	private double fitness = 0;
	
	public RepeatableSharedMemory() {		
		this.memory = new ArrayList();
	}
		
	public void add(MemoryIndividual field) {
		synchronized ( RepeatableSharedMemory.SEMAPHORE ) {
			for (Iterator iter = memory.iterator(); iter.hasNext();) {
				MemoryIndividual element = (MemoryIndividual) iter.next();
				Individual indivudal = element.getIndividual();
				
				
				if ( indivudal.getSpeciesCount() == field.getIndividual().getSpeciesCount() ) {
					memory.remove(element);
					break;
				}
			}
			memory.add(field);
		}	
	}
	
	public MemoryIndividual getIndividual(int specieCount) {
		MemoryIndividual result = null;
		for (Iterator iter = memory.iterator(); iter.hasNext();) {
			MemoryIndividual element = (MemoryIndividual) iter.next();
			
			if ( element.getIndividual().getSpeciesCount() == specieCount ) {
				result = element;
				break;
			}
		}
		return result;
	}
	
	public synchronized ArrayList getElements() {
		return memory;
	}

	public int getSize() {
		return memory.size();
	}

	public double getFitness() {
		return fitness;
	}

	public void setFitness(double fitness) {
		this.fitness = fitness;
	}

	public ArrayList getMemory() {
		return memory;
	}

	public void setMemory(ArrayList memory) {
		this.memory = memory;
	}
	
}
